import axios from 'axios'
import Vue from 'vue'
import router from '../router';
let vue = new Vue()

const baseUrl = 'http://cun.lexhua.com/member/'
const baseUrlApi = 'http://cun.lexhua.com/api/'
// 超时设置，若30秒之后还在加载中，终止或跳转 
axios.defaults.timeout = 30000
// 添加响应拦截器
axios.interceptors.response.use(
  function (response) {
    //可以写if判断，提前拦截错误信息
    // console.log(response) //在获取的接口中的数据之前打印接口中的数据，所以可以在这里判断status状态码
    if (response.status==200) {
      return response;
    } else if(response.status==404){
    } else if(response.status==500){ 
    }

  }, function (err) {
    return Promise.reject(err)
})

/*POST*/
const apiPost = (url, params = {}) => {
	return new Promise((resolve, reject) => {
		axios({
			method: 'post',
			url:baseUrl + url,
			data:params,
			headers:{"token": localStorage.getItem('adm_token')}
		}).then(res => {
			if(res.data.code == 301) {
				localStorage.setItem(null, res.data.token)
				window.location.href = '#/login'
				return false
			}
			resolve(res.data);
		}).catch(err =>{
			reject(err.data)
		})
	})
}
/*POST*/
const apiPosts = (url, params = {}) => {
	return new Promise((resolve, reject) => {
		axios({
			method: 'post',
			url:baseUrlApi + url,
			data:params,
			headers:{"adm_token": localStorage.getItem('adm_token')}
		}).then(res => {
			if(res.data.code == 301) {
				localStorage.setItem(null, res.data.token)
				window.location.href = '#/login'
				return false
			}
			resolve(res.data);
		}).catch(err =>{
			reject(err.data)
		})
	})
}
/*POST FILE*/
const postFile = (url, params = {}) => {
	return new Promise((resolve, reject) => {
		axios({
			method: 'post',
			url:baseUrl + url,
			data:params,
			headers:{
			    'Content-Type': 'multipart/form-data'
			},  
		}).then(res => {
			if(res.data.code == 301) {
				localStorage.setItem(null, res.data.token)
				window.location.href = '#/login'
				return false
			}
			resolve(res.data);
		}).catch(err =>{
			reject(err.data)
		})
	})
}

/*修改属性*/
const updateStatus = (url, params = {}) => {
	axios({
		method: 'post',
		url:baseUrl + url,
		data:params,
		herader:{"adm_token": sessionStorage.getItem('adm_token')}
	}).then(res => {
		vue.$message(res.data.msg)
	}).catch(err =>{
		vue.$message.error(err)
	})
}


export default {
	apiPost: apiPost,
	apiPosts: apiPosts,
	updateStatus: updateStatus,
	postFile: postFile,
}